package com.atguigu.gulimall.product.service.impl;

import com.alibaba.druid.sql.PagerUtils;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.service.ProductAttrValueService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVO;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVO;
import com.atguigu.gulimall.product.vo.AttrResponseVO;
import com.atguigu.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        // Spring工具类 BeanUtils.coppProperties
        // 1.保存基本数据
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //基本类型 才有属性分组
            if (attr.getAttrGroupId() != null) {
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attrEntity.getAttrId());
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationDao.insert(relationEntity);
            }

        }


    }

    @Override
    public PageUtils queryList(Map<String, Object> params, Long categoryId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", type.equalsIgnoreCase("base")
                        ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (categoryId == 0) {
            if (!StringUtils.isEmpty(key)) {
                wrapper.eq("attr_id", key).or().like("attr_name", key);

            }
        } else {
            wrapper.eq("catelog_id", categoryId);
            if (!StringUtils.isEmpty(key)) {
                wrapper.and((obj) -> {
                    obj.eq("attr_id", key).or().like("attr_name", key);
                });
            }


        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVO> respVOS = records.stream().map((attrEntity) -> {
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            BeanUtils.copyProperties(attrEntity, attrResponseVO);
            //设置分类名字
            Long catelogId = attrEntity.getAttrId();
            if (catelogId != null) {
                String categoryName = categoryDao.selectById(attrEntity.getCatelogId()).getName();
                attrResponseVO.setCatelogName(categoryName);
            }
            //设置分组的名字
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null) {

                Long attrGroupId = relationEntity.getAttrGroupId();
                if (attrGroupId != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    attrResponseVO.setAttrGroupId(attrGroupId);
                    attrResponseVO.setGroupName(attrGroupName);
                }
            }

            return attrResponseVO;
        }).collect(Collectors.toList());
        pageUtils.setList(respVOS);
        return pageUtils;

    }

    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrResponseVO responseVO = new AttrResponseVO();
        BeanUtils.copyProperties(attrEntity, responseVO);
        //所属分类
        Long catelogId = attrEntity.getCatelogId();
        Long[] categoryPath = categoryService.findCategoryPath(catelogId);
        responseVO.setCatelogPath(categoryPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            responseVO.setCatelogName(categoryEntity.getName());
        }

        if (attrEntity.getAttrType() == (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            //所属分组id
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if (relationEntity != null) {
                Long attrGroupId = relationEntity.getAttrGroupId();
                if (attrGroupId != null) {
                    responseVO.setAttrGroupId(attrGroupId);
                }
            }

        }


        return responseVO;


    }

    @Override
    @Transactional
    public void updateAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //修改基本信息
        this.updateById(attrEntity);

        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attrEntity.getAttrId());
        if (attrEntity.getAttrType() == (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if (count > 0) {
                //修改关联的分组信息

                attrAttrgroupRelationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
            } else {
                //新增分组信息
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<AttrEntity> getRelationAttr(Long groupId) {

        if (groupId != null) {

            List<AttrAttrgroupRelationEntity> attrGroups = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", groupId));
            List<Long> attrIds = attrGroups.stream().map((relation) -> {
                return relation.getAttrId();
            }).collect(Collectors.toList());

            Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;

        }
        return null;
    }


    @Override
    public void deleteRelation(List<AttrGroupRelationVO> attrGroupRelationVOs) {
//        attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",1L).eq("attr_group_id",1L));
        //批量删除
        //delete from relation where attr_id = ? and attr_group_id = ?
        attrAttrgroupRelationDao.delectRelationBatch(attrGroupRelationVOs);

    }

    /**
     * 当前分组没有关联的所有属性
     *
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
//        //1.当前分组只能关联自己所属分类里面的所有基本属性
//        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
//        //分组信息
//        Long catelogId = attrGroupEntity.getCatelogId();

        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(params);

        IPage<AttrEntity> attrEntityIPage = attrDao.noRelationAttr(page, attrGroupId);
        return new PageUtils(attrEntityIPage);


        /**
         * select * from pms_attr where attr_type=1 and attr_id not in(
         *     select attr_id from pms_attr_attrgroup_relation where attr_group_id = 2)
         *     and catelog_id = (select catelog_id from pms_attr_group where attr_group_id = 2);
         */

//        //2.当前分组只能关联别的分组没有引用的属性 ???
//        //2.1当前分类其他的分组
//        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
//                .eq("catelog_id", catelogId).ne("attr_group_id", attrGroupId));
//        List<Long> groupIds = groups.stream().map((group) -> {
//            return group.getAttrGroupId();
//        }).collect(Collectors.toList());
//        //2.2这些分组关联的属性
//        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
//                .in("attr_group_id", groupIds));
//        List<Long> attrIds = relations.stream().map((relation) -> {
//            return relation.getAttrId();
//        }).collect(Collectors.toList());
//        //2.3当前分类所有属性移除这些属性
//        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
//                .eq("catelog_id", catelogId));
//        if(attrIds==null||attrIds.isEmpty()){
//            wrapper.notIn("attr_id", attrIds);
//
//        }
////        List<AttrEntity> noAttrs = attrDao.selectList(wrapper);
//        String key = (String) params.get("key");
//        if(!StringUtils.isEmpty(key)){
//            wrapper.and((obj)->{
//                obj.eq("attr_id",key).or().like("attr_name",key);
//            });
//        }

//        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params));
//        page.setRecords(entities);
//        return new PageUtils(page);
    }

    @Override
    public void saveRelation(List<AttrGroupRelationVO> attrGroupRelationVOs) {
        attrAttrgroupRelationDao.insertBatch(attrGroupRelationVOs);

    }

    /**
     * 获取分类关联的分组和关联属性
     *
     * @param catalogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVO> withAttr(Long catalogId) {
//        List<AttrGroupWithAttrsVO> list = new ArrayList<>();
        //获取分类关联的分组列表
        List<AttrGroupEntity> attrGroups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catalogId));

        List<AttrGroupWithAttrsVO> respVOs = attrGroups.stream().map((attrGroup) -> {
            AttrGroupWithAttrsVO attrGroupWithAttrsVO = new AttrGroupWithAttrsVO();
            //分组信息
            BeanUtils.copyProperties(attrGroup, attrGroupWithAttrsVO);
            List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", attrGroup.getAttrGroupId()));
            //设置 attrs 详细属性信息
            //todo attrs怎么只有一个
//            List<AttrVO> relationAttrVOs = this.getRelationAttrVOs(attrGroup.getAttrGroupId());
            List<AttrVO> attrs = relations.stream().map((relation) -> {
                Long attrId = relation.getAttrId();
                AttrEntity attrEntity = attrDao.selectById(attrId);
                AttrVO attrVO = new AttrVO();
                BeanUtils.copyProperties(attrEntity, attrVO);
                attrVO.setAttrGroupId(relation.getAttrGroupId());
                return attrVO;
            }).collect(Collectors.toList());
            attrGroupWithAttrsVO.setAttrs(attrs);

//
//            for (AttrAttrgroupRelationEntity relation : relations) {
//                List<AttrEntity> attrEntities = attrDao.selectList(new QueryWrapper<AttrEntity>().eq("attr_id", relation.getAttrId()));
//                List<AttrVO> attrs = attrEntities.stream().map(attrEntity -> {
//                    AttrVO attrVO = new AttrVO();
//                    BeanUtils.copyProperties(attrEntity, attrVO);
//                    attrVO.setAttrGroupId(attrGroup.getAttrGroupId());
//                    return attrVO;
//                }).collect(Collectors.toList());
//                attrGroupWithAttrsVO.setAttrs(attrs);
//            }
            return attrGroupWithAttrsVO;
        }).collect(Collectors.toList());
        return respVOs;

    }

    @Override
    public List<ProductAttrValueEntity> listForSpu(Long spuId) {
        return productAttrValueService.getBaseMapper().selectList(new QueryWrapper<ProductAttrValueEntity>()
                .eq("spu_id", spuId));

    }

    @Override
    @Transactional
    public void updateSpu(Long spuId, List<ProductAttrValueEntity> entities) {
        productAttrValueService.getBaseMapper().delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));


        List<ProductAttrValueEntity> collect = entities.stream().map(entity -> {
            entity.setSpuId(spuId);
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return attrIds.stream().filter(attrId -> {
            return 1 == this.getById(attrId).getSearchType();
        }).collect(Collectors.toList());
    }


}